<?php

/**
 * класс для работы с таблицей категорий
 *
 * @author kingop
 */
class DatabaseObject_Basket extends DatabaseObject {
    /* status = array(
     *          'cart'=>'в корзине',
     *          'wish' => 'избранное' // не работает
     *         
     * ); */

    public $shop = null;
    public $user = null;
    public $product = null;

    public function __construct($db) {
        parent::__construct($db, 'basket', 'id');

        // далее перечислены все поля таблицы

        $this->add('userId');
        $this->add('productId');
        $this->add('count');
        $this->add('shopId');
        $this->add('status');
    }

    protected function postLoad() {
        parent::postLoad();

        // загрузим прикрпленные файлы
        $user = new DatabaseObject_User($this->getDb());
        $shop = new DatabaseObject_User($this->getDb());
        $product = new DatabaseObject_Products($this->getDb());
        $user->load($this->userId);
        $shop->load($this->shopId);
        $product->load($this->productId);
        $this->user = $user;
        $this->shop = $shop;
        $this->product = $product;

        return true;
    }

    public static function GetBasket($db, $options = array()) {
        // инициализируем настройки
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'b.id'
        );

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'b.*');

        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);
        if ($options['where'])
            $select->where($options['where']);

        $select->order($options['order']);

        // получим данные из базы
        $data = $db->fetchAll($select);

        // сделаем из полученных записей объекты класса
        $cats = self::BuildMultiple($db, __CLASS__, $data);
        $cat_ids = array_keys($cats);
        if (count($cat_ids) > 0)
            foreach ($cats as $key => $value) {
                $user = new DatabaseObject_User($db);
                $shop = new DatabaseObject_User($db);
                $product = new DatabaseObject_Products($db);
                $user->load($value->userId);
                $shop->load($value->shopId);
                $product->load($value->productId);
                $value->user = $user;
                $value->shop = $shop;
                $value->product = $product;
            }
        if (count($cat_ids) == 0)
            return array();

        return $cats;
    }

    private static function _GetBaseQuery($db, $options) {
        // инициализация настроек
        $defaults = array();

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        // создание запроса на получение
        $select = $db->select();
        $select->from(array('b' => 'basket'), array());

        return $select;
    }

    public static function GetCount($db) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');

        return $db->fetchOne($select);
    }

    // Изменение количество товара покупкив корзине
    public static function SetProductCount($db, $id, $count) {
        $cart = new DatabaseObject_Basket($db);
        $cart->load($id);
        $cart->count = $count;
        $cart->save();

        return true;
    }

    // Получение количество товаров в корзине
    public static function GetCountUserBascket($db, $userId, $status = 'cart') {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        $select->where('userId = ?', $userId);
        $select->where('status = ?', $status);
        return $db->fetchOne($select);
    }

    //
    public static function GetCountProductBascket($db, $productId, $userId, $status = 'cart') {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        $select->where('userId = ?', $userId);
        $select->where('productId = ?', $productId);
        $select->where('status = ?', $status);
        $count = $db->fetchOne($select);
        if ($count > 0) {
            $select = self::_GetBaseQuery($db, array());
            $select->from(null, '*');
            $select->where('userId = ?', $userId);
            $select->where('productId = ?', $productId);
            $select->where('status = ?', $status);
            return $db->fetchOne($select);
        } else {
            return false;
        }
    }

    // Получение полной корзины зарегестрированного пользователя  
    public static function GetUserBascket($db, $userId, $status = 'cart') {
        $select = self::_GetBaseQuery($db, array());
        $select->distinct();
        $select->from(null, 'b.shopId');
        $select->where('userId = ?', $userId);
        if (gettype($status) == 'array') {
            foreach ($status as $k => $v) {
                $status1.="'" . $v . "',";
            }
            $status1 = trim($status1, ',');
            $select->where('status in (' . $status1 . ')');
        } else {
            $select->where('status = ?', $status);
        }

        $data = $db->fetchAll($select);
        foreach ($data as $k => $v) {
            $user = new DatabaseObject_User($db);
            $user->load($v['shopId']);
            $data[$k]['user'] = $user;

            $select = self::_GetBaseQuery($db, array());
            $select->from(null, 'b.*');
            $select->where('shopId = ?', $v['shopId']);
            $select->where('userId = ?', $userId);
            if (gettype($status) == 'array') {

                $select->where('status in (' . $status1 . ')');
            } else {
                $select->where('status = ?', $status);
            }
            $prod = $db->fetchAll($select);
            $price = 0;
            foreach ($prod as $m => $p) {
                $product = new DatabaseObject_Products($db);
                $product->load($p['productId']);

                $data[$k]['products'][] = $product;
                $data[$k]['cartId'][] = $prod[$m]['id'];
                $data[$k]['count'][] = $prod[$m]['count'];
                $data[$k]['priceproduct'][] = $prod[$m]['count'] * $product->price;
                $price += $prod[$m]['count'] * $product->price;
            }

            $data[$k]['price'] = $price;
        }
        return $data;
    }

    // Получение полной корзины гостя
    public static function GetUserSessionBascket($db, $status = 'cart') {
        foreach ($_SESSION['cart'] as $k => $v) {
            $user = new DatabaseObject_User($db);
            $user->load($k);
            $data[$k]['user'] = $user;

            $price = 0;
            foreach ($v as $m => $p) {
                $product = new DatabaseObject_Products($db);
                $product->load($m);

                $data[$k]['products'][] = $product;
                $data[$k]['cartId'][] = 1;
                $data[$k]['count'][] = $p;
                $data[$k]['priceproduct'][] = $p * $product->price;
                $price += $p * $product->price;
            }

            $data[$k]['price'] = $price;
        }
        return $data;
    }

    // удаление корзины пользоватля
    public static function DeleteUserBascket($db, $userId, $status = 'cart') {
        $db->query("DELETE FROM basket WHERE userID = '$userId' and status='$status'");
        return true;
    }

    // Удаление продукта из корзины
    public static function DeleteItemBascket($db, $item, $userId, $status = 'cart') {
        $db->query("DELETE FROM basket WHERE userID = '$userId' and productId = '$item' and status='$status'");
        return true;
    }

    // удаление магазина из корзины
    public static function DeleteShopBascket($db, $shop, $userId, $status = 'cart') {
        $db->query("DELETE FROM basket WHERE userID = '$userId' and shopId = '$shop' and status='$status' ");
        return true;
    }

    // получение миникорзины зарегистрированого пользователя
    public static function GetCart($db, $userId, $status = 'cart') {
        $count = DatabaseObject_Basket::GetCountUserBascket($db, $userId, $status);
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'b.*');
        $select->where('userId = ?', $userId);
        $select->where('status = ?', $status);
        $data = $db->fetchAll($select);
        $price = 0;
        foreach ($data as $k => $v) {
            $product = new DatabaseObject_Products($db);
            $product->load($v['productId']);
            $price += $product->price * $v['count'];
        }
        $cart = array();
        $cart['price'] = $price;
        $cart['count'] = $count;
        return $cart;
    }

    // получение списка продуктов магазина shopId пользователя userId 
    public static function GetProductShopUser($db, $userId, $shopId) {
        $status = 'cart';
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'b.*');
        $select->where('shopId = ?', $shopId);
        $select->where('userId = ?', $userId);
        $select->where('status = ?', $status);
        $prod = $db->fetchAll($select);
        $price = 0;
        foreach ($prod as $m => $p) {
            $product = new DatabaseObject_Products($db);
            $product->load($p['productId']);

            $data['products'][] = $product;
            $data['cartId'][] = $prod[$m]['id'];
            $data['count'][] = $prod[$m]['count'];
            $data['priceproduct'][] = $prod[$m]['count'] * $product->price;
            $price += $prod[$m]['count'] * $product->price;
        }

        $data['price'] = $price;
        return $data;
    }

    // может ли пользователь оставить комментарий магазину
    public static function canWriteComment($db, $userId, $shopId) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        $select->where('userId = ?', $userId);
        $select->where('shopId = ?', $shopId);
        $select->where("status = 'deviation' or `status` = 'finished'");
        return $db->fetchOne($select) > 0;
    }

}

?>
